/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.systhreads;

import fr.x9c.cadmium.kernel.Context;
import fr.x9c.cadmium.kernel.Fail;
import fr.x9c.cadmium.kernel.FalseExit;

/**
 * This implements a basic mutex (also referred to as lock). <br/>
 * Contrary to JDK locks, no restriction is imposed on which thread can
 * release a mutex. <br/>
 * A thread waiting on a mutex cannot be interrupted.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
final class Mutex {

    /** Mutex state. */
    private boolean locked;

    /**
     * Constructs a new mutex. <br/>
     * The mutex is not locked.
     */
    Mutex() {
        this.locked = false;
    } // end empty constructor

    /**
     * Acquires / locks the mutex.
     * @param ctxt context - should not be <tt>null</tt>
     * @throws FalseExit if another threads has exited the program
     * @throws Fail.Exception if an asynchronous exception should be thrown
     */
    synchronized void lock(final Context ctxt)
        throws FalseExit, Fail.Exception {
        while (this.locked) {
            try {
                wait();
            } catch (final InterruptedException ie) {
                final FalseExit fe = FalseExit.createFromContext(ctxt);
                fe.fillInStackTrace();
                throw fe;
            } // end try/catch
        } // end while
        this.locked = true;
    } // end method 'lock()'

    /**
     * Releases / unlocks the mutex.
     */
    synchronized void unlock() {
        this.locked = false;
        notifyAll();
    } // end method 'unlock()'

    /**
     * Tries to acquire / lock the mutex, returning immediately if the mutex
     * is already acquired / locked.
     * @return <tt>true</tt> if the lock has been acquired,
     *         <tt>false</tt> otherwise
     */
    synchronized boolean tryLock() {
        if (this.locked) {
            return false;
        } else {
            this.locked = true;
            return true;
        } // end if/else
    } // end method 'tryLock()'

} // end class 'Mutex'
